package com.jintoufs.web.action.hotel;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.QueryRule;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.constants.FullCalendar;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.date.DateBean;
import com.jintoufs.domain.hotel.HotelPrice;
import com.jintoufs.domain.hotel.HotelRoom;
import com.jintoufs.domain.images.Images;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.date.DateBeanService;
import com.jintoufs.service.features.FeaturesService;
import com.jintoufs.service.hotel.HotelRoomService;
import com.jintoufs.service.image.ImageService;
import com.jintoufs.util.date.DateUtils;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("room")
public class RoomAction extends SupportAction{
    @Resource
    private DateBeanService dateBeanService;
    @Resource
    private HotelRoomService hotelRoomService;
    @Resource
    private FeaturesService featuresService;
    @Resource
    private ImageService imageService;

    @RequestMapping("list")
    public String list(String id,Model model) {
        model.addAttribute("hotelId",id);
        return "/hotel/room/list";
    }

    @RequestMapping("/oper")
    @SystemControllerLog(description = "房间")
    public void oper(HttpServletResponse response, String _id, String oper, HotelRoom hotelRoom,String imgUrl) {
        AjaxMsg ajaxMsg = new AjaxMsg();

        try {
            if (oper.equals("del") && _id != null) {
                hotelRoomService.delete(_id);

            } else {

                switch (oper) {
                    case "edit":
                        if (!ValidUtil.isEmpty(hotelRoom.getHotelId())){
                            hotelRoomService.update(hotelRoom);
                            ajaxMsg.setCode("200");
                            ajaxMsg.setMessage("更新成功");
                        }else {
                            ajaxMsg.setCode("500");
                            ajaxMsg.setMessage("更新房间失败");
                        }
                        break;
                    case "add":
                        String id = getUUID();
                        hotelRoom.setId(id);
                        if (!ValidUtil.isEmpty(hotelRoom.getHotelId())){
                            hotelRoom.setStatus("1");
                            HotelRoom tmp = hotelRoomService.add(hotelRoom);
                            if (imgUrl!=null){
                                Images images = new Images();
                                images.setId(getUUID());
                                images.setPath(imgUrl);
                                images.setCreateTime(new Date());
                                images.setValueId(id);
                                images.setCover("1");
                                imageService.insert(images);
                            }
                            if (tmp == null) {
                                ajaxMsg.setCode("500");
                                ajaxMsg.setMessage("添加房间失败");
                            } else {
                                ajaxMsg.setCode("200");
                                ajaxMsg.setMessage("添加房间成功");
                            }
                        }else {
                            ajaxMsg.setCode("500");
                            ajaxMsg.setMessage("添加房间失败");
                        }
                        break;
                    default:
                        ajaxMsg.setCode("500");
                        ajaxMsg.setMessage("操作代码错误！系统只提供增加/修改/删除功能。");
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode("500");
            if (e instanceof DuplicateKeyException) {
//                ajaxMsg.setMessage("此酒店名已存在！");
//            } else {
                ajaxMsg.setMessage("程序出错，请联系管理员！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    @RequestMapping("/delete")
    @SystemControllerLog(description = "删除酒店")
    public void delete(HttpServletResponse response, String[] id) {
        for (String _id : id) {
            hotelRoomService.delete(_id);
        }
        writeInfo(response, JSON.toJSONString(new AjaxMsg()));
    }

    @RequestMapping("/query")
    @ResponseBody
    @SystemControllerLog(description = "获取酒店房间列表")
    public JqgridPage query(String hotelId, int page, int rows, String sidx,
                            String sord, String filters, @CurrentUser Customer customer) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        QueryRule role = new QueryRule();
        role.setField("customer_id");
        role.setOp("eq");
        role.setData(customer.getId());
        filters_.getRules().add(role);
        if (!ValidUtil.isEmpty(hotelId)){
            role = new QueryRule();
            role.setOp("eq");
            role.setField("h.id");
            role.setData(hotelId);
            filters_.getRules().add(role);
        }
        List<Map<String,Object>> list = hotelRoomService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }


    @RequestMapping("/input")
    @SystemControllerLog(description = "查看房间详细信息")
    public String input(String id, Model model,String isEdit,String hotelId) {
        Map<String, Object> result = new HashMap<>();
        Map<String,Object> param = new HashMap<>();
        if (!ValidUtil.isEmpty(id)) {
            param.put("valueId",id);
            result.put("hotelRoom", hotelRoomService.queryById(id));
            result.put("features", featuresService.selectByParams(param));
        }
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("hotelId", hotelId);
        model.addAttribute("result", result);
        model.addAttribute("title", "房间详细信息");
        return "hotel/room/input";
    }



    @RequestMapping("priceCalendar")
    public String priceCalendar(String id,Model model){
        model.addAttribute("roomId",id);
        return "hotel/room/priceCalendar";
    }

    @RequestMapping("/getPriceCalendar/{id}")
    public void getPriceCalendar(@PathVariable String id, String start,String end, HttpServletResponse response){
        Map<String,Object> param = new HashMap<>(1);
        param.put("roomId",id);
        param.put("start",start);
        param.put("end",end);
        List<FullCalendar> priceCalendar = hotelRoomService.getPriceCalendar(param);

        writeInfo(response,JSON.toJSONString(priceCalendar));
    }


    @RequestMapping("/setPriceCalendar")
    @ResponseBody
    public AjaxMsg setPriceCalendar(HotelPrice hotelPrice){
        AjaxMsg ajaxMsg = new AjaxMsg();
        hotelPrice.setHotelId(hotelRoomService.queryById(hotelPrice.getHotelRoomId()).getHotelId());
        HotelPrice nowHotelPrice = hotelRoomService.selectByHotelPrice(hotelPrice);
        try {
            if (!ValidUtil.isEmpty(nowHotelPrice)){
                hotelPrice.setReserve(nowHotelPrice.getReserve());
                hotelRoomService.updatePrice(hotelPrice);
            }else {
                hotelPrice.setId(getUUID());
                hotelPrice.setReserve(hotelRoomService.selectById(hotelPrice.getHotelRoomId()).getNumber());
                hotelRoomService.savePrice(hotelPrice);
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode("500");
            ajaxMsg.setMessage("系统错误");
        }
        return ajaxMsg;
    }


    @RequestMapping("pricealendar2")
    public String priceCalendar2(String id,Model model){
        Map<String,Object> param = new HashMap<>(3);
        param.put("roomId",id);
        param.put("date",DateUtils.getDate("yyyy-MM"));
        List<Map<String,Object>> priceCalendar = hotelRoomService.getPriceCalendar2(param);
        DateBean dateBean = dateBeanService.getLast();
        model.addAttribute("priceCalendar",JSON.toJSONString(priceCalendar));
        model.addAttribute("dateBean",dateBean.getDate());
        model.addAttribute("roomId",id);
        return "/hotel/room/pricecalendar2";
    }

    @RequestMapping("/getpricecalendar2/{id}")
    public void getPriceCalendar2(@PathVariable String id, String date, HttpServletResponse response){
        Map<String,Object> param = new HashMap<>(1);
        param.put("roomId",id);
        param.put("date",DateUtils.getNextMonth(date,"yyyy-MM"));
        List<Map<String,Object>> priceCalendar = hotelRoomService.getPriceCalendar2(param);
        writeInfo(response,JSON.toJSONString(priceCalendar));
    }

    @RequestMapping("/setpricecalendar2/{id}")
    @ResponseBody
    public AjaxMsg setPriceCalendar(@PathVariable String id,String data,String dates){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            HotelRoom hotelRoom = hotelRoomService.selectById(id);
            data = data.replace("开启","1").replace("关闭","0");
            HotelPrice priceData = JSON.parseObject(data,HotelPrice.class);
            priceData.setHotelRoomId(id);
            HotelPrice nowHotelPrice;
            priceData.setHotelId(hotelRoom.getHotelId());
            if (!ValidUtil.isEmpty(dates)){
                List datesList = JSON.parseObject(dates,List.class);
                for (Object date:datesList){
                    priceData.setDate(DateUtils.parseDate(date.toString(),"yyyy-MM-dd"));
                    nowHotelPrice = hotelRoomService.selectByHotelPrice(priceData);
                    if (!ValidUtil.isEmpty(nowHotelPrice)){
                        hotelRoomService.updatePrice(priceData);
                    }else {
                        priceData.setId(getUUID());
                        hotelRoomService.savePrice(priceData);
                    }
                }
            }else {
                nowHotelPrice = hotelRoomService.selectByHotelPrice(priceData);
                if (!ValidUtil.isEmpty(nowHotelPrice)){
                    hotelRoomService.updatePrice(priceData);
                }else {
                    priceData.setId(getUUID());
                    hotelRoomService.savePrice(priceData);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("服务器发生错误可能部分或所有为设置完成");
        }
        return ajaxMsg;
    }

    @RequestMapping("/changeStatus")
    @ResponseBody
    @SystemControllerLog(description = "更新鱼·定制产品状态")
    public AjaxMsg changeStatus(HttpServletResponse response, String valueId) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        HotelRoom hotelRoom = hotelRoomService.queryById(valueId);
        if (Constants.RES_STATUS_NORMAL.equals(hotelRoom.getStatus())) {
            hotelRoom.setStatus(Constants.RES_STATUS_DELETE);
        } else {
            hotelRoom.setStatus(Constants.RES_STATUS_NORMAL);
        }
        hotelRoomService.update(hotelRoom);
        return ajaxMsg;
    }

}
